<template>
  <div>
     <el-upload
      action=""
      :data="dataObj"
      list-type="picture-card"
      :file-list="fileList"
      :limit="maxCount"
      :on-success="handleUploadSuccess"
      :on-remove="handleRemove"
      :on-preview="handlePreview"
      :on-exceed="handleExceed"
      :http-request="uploadSectionFile"
    >
    <!-- <el-upload
      action=""
      :data="dataObj"
      list-type="picture-card"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
      :limit="maxCount"
      :on-exceed="handleExceed"
    > -->
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
  import {policy} from '@/api/oss'
  import {cos,cos_delete} from '@/utils/cos'
  import random_string from '@/utils/randomString'
  export default {
    name: 'multiUpload',
    props: {
      //图片属性数组
      value: Array,
      //最大上传图片数量
      maxCount:{
        type:Number,
        default:1
      },
      leibie:String
    },
    data() {
      return {
        dataObj: {
          policy: '',
          signature: '',
          key: '',
          ossaccessKeyId: '',
          dir: '',
          host: ''
        },
        dialogVisible: false,
        dialogImageUrl:null
      };
    },
    computed: {
      fileList() {
        if(this.value===undefined||this.value==null||this.value===''){
            return
          }
        let fileList=[];
        for(let i=0;i<this.value.length;i++){
          fileList.push({url:this.value[i]});
        }
        return fileList;
        }
    },

    methods: {
      emitInput(fileList) {
        let value=[];
        for(let i=0;i<fileList.length;i++){
          value.push(fileList[i].url);
        }
        this.$emit('input', value)
      },
      handleRemove(file, fileList) {
        console.log('执行了删除操作',file)
        console.log('删除后：',fileList)
        cos_delete(file.url.slice(50)).then(res => {
          this.emitInput(fileList);
        })
      },
      handlePreview(file) {
        console.log('执行点击图片方法')
        this.dialogVisible = true;
        this.dialogImageUrl=file.url;
      },
      uploadSectionFile(params){
        var _self = this;
        console.log('执行自定义上传方法',params)
        var file = params.file;
        console.log('dx:',file.type,file.size / 1024)
        const isType = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
        const isSize = file.size / 1024 < 500;
        if (!isType) {
          this.$message.error('上传图片只能是 jpg/png/gif 格式!');
          params.onError()
          return
        }
        if (!isSize) {
          this.$message.error('上传图片大小不能超过 500kb!');
          params.onError()
          return
        }
        let fileName = file.name;
        let cosFileNeme = this.leibie + '_' + (new Date()).getTime() + '_' + random_string(6) + fileName.substring(fileName.lastIndexOf('.'));
         cos.putObject({
              Bucket: 'wx-1256614213', /* 必须 */
              Region: 'ap-shanghai',     /* 存储桶所在地域，必须字段 */
              Key: cosFileNeme,              /* 必须 */
              Body: file, // 上传文件对象
              onProgress: function(progressData) {
                let data = JSON.stringify(progressData)
                  console.log('打印上传返回结果：',data);
                  params.onProgress({ percent: progressData.percent * 100})
              }
          }, function(err, data) {
            console.log(err || data);
            if(data){
              console.log('上传成功')
              params.onSuccess({url:'http://'+data.Location})
            }else{
              console.log('上传失败')
              params.onError()
            }
          });
      },
       handleUploadSuccess(res, file) {
         console.log(res)
        console.log('执行上传成功方法')
        this.fileList.push({name: file.name,url:res.url});
        console.log(this.fileList)
        this.emitInput(this.fileList);
      },
      handleExceed(files, fileList) {
        this.$message({
          message: '最多只能上传'+this.maxCount+'张图片',
          type: 'warning',
          duration:1000
        });
      },
    }
  }
</script>
<style>

</style>

